package com.g8.pethospitallearnbackend.controller;

import com.g8.pethospitallearnbackend.entity.PermissionModifyInBulk;
import com.g8.pethospitallearnbackend.entity.User;
import com.g8.pethospitallearnbackend.entity.StringList;
import com.g8.pethospitallearnbackend.exception.CustomException;
import com.g8.pethospitallearnbackend.exception.NoDataException;
import com.g8.pethospitallearnbackend.interceptors.AuthRequird;
import com.g8.pethospitallearnbackend.service.UserService;
import com.g8.pethospitallearnbackend.utils.responseUtil.ResponseStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
@AuthRequird // 表明需要权限控制
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping
    public String print(){
        return "Hello!";
    }

    @AuthRequird(required = false)
    @PostMapping("/test")
    public Map<String,Object> test(){
        Map<String, Object> map = new HashMap<>();
        log.info("需要验证token的函数执行了...");
        map.put("state",true);
        map.put("msg","请求成功");
        return map;
    }

    @GetMapping("/{userId}")
    public User getUserInfoById(@PathVariable("userId") String userId){
        User user = userService.getUserById(userId);
        // 如果能查到，就返回数据
        if (user != null) return user;
            // 如果查不到，那就抛出“未查询到相关数据”的异常
        else throw new NoDataException();
    }

    @PutMapping("/modify/{userId}")
    public User modifyUser(@PathVariable String userId, @RequestBody User user) {
        user.setUserId(userId);
        return userService.modifyAUser(user);
    }

    @GetMapping("/all/{role}")
    public List<User> getUserOfARole(@PathVariable Integer role) {
        Byte roleByte = null;
        if (role == 0) roleByte = 0;
        else if (role == 1) roleByte = 1;
        else throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "role只能是0或1");
        return userService.getUserOfARole(roleByte);
    }

    @DeleteMapping("/{userId}")
    public String deleteAUser(@PathVariable String userId) {
        return userService.deleteAUser(userId);
    }

    @PostMapping("")
    public User addAUser(@RequestBody User user) {
        return userService.addAUser(user);
    }

    @PutMapping("/permission")
    public User modifyPermission(@RequestBody User user) {
        return userService.modifyPermission(user);
    }

    @DeleteMapping("")
    public String deleteUserInBulk(@RequestBody StringList userIds) {
        return userService.deleteUserInBulk(userIds);
    }

    @PutMapping("/permissions")
    public String modifyPermissionsInBulk(@RequestBody PermissionModifyInBulk perModiInBulk) {
        return userService.modifyPermissionsInBulk(perModiInBulk);
    }

}
